package cn.itsource.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.itsource.basic.exception.BusinessException;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.utils.AjaxResult;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.mapper.LogininfoMapper;
import cn.itsource.user.mapper.UserMapper;
import cn.itsource.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JavaMailSender javaMailSender;


    //处理用户信息回回显
    @Override
    public User handleUser(Long logininfoId) {
        return userMapper.findByLogininfoId(logininfoId);
    }

    //修改个人信息数据
    @Override
    @Transactional
    public AjaxResult modifyUser(User user) {
        userMapper.update(user);
        Logininfo logininfo = logininfoMapper.findOne(user.getLogininfoId());
        logininfo.setUsername(user.getUsername());
        logininfo.setPhone(user.getPhone());
        logininfo.setEmail(user.getEmail());
        logininfoMapper.update(logininfo);
        return new AjaxResult();
    }

    //修改状态
    @Override
    @Transactional
    public AjaxResult handleState(User user) {
        // 员工状态 - 1启用，0禁用
        if (user.getState() == 1) {
            user.setState(0);
        } else {
            user.setState(1);
        }
        userMapper.update(user);
        return new AjaxResult();
    }

    @Override
    @Transactional
    public void delete(Long id) {
        User user = userMapper.findOne(id);
        //先删除t_logininfo表
        logininfoMapper.delete(user.getLogininfoId());
        //删除t_user表一条数据
        super.delete(id);
    }

    @Override
    @Transactional
    public void patchdel(Long[] ids) {
        for (Long id : ids) {
            delete(id);
        }
    }

    //电话号注册
    @Override
    @Transactional
    public void registerPhone(Map<String, String> map) {

        String phone = map.get("phone"); //电话号码
        String smsCode = map.get("smsCode");//输入的短信验证码
        String password = map.get("password");//密码
        String passwordRepeat = map.get("passwordRepeat");//确认密码
        //1.校验空值
        if (StrUtil.isBlank(phone) || StrUtil.isBlank(smsCode) ||
                StrUtil.isBlank(password) || StrUtil.isBlank(passwordRepeat)) {
            throw new BusinessException("请填写完整信息");
        }
        //2.校验短信验证码 获取redis的手机短信验证码【register:18455669988 - 764347:1715413642524】
        Object obj = redisTemplate.opsForValue().get("register:" + phone);//764347:1715413642524
        if (obj == null) {
            throw new BusinessException("手机短信验证码已过期");
        } else {
            //手机短信验证码存在  校验是否相等
            if (!obj.toString().split(":")[0].equals(smsCode)) {
                throw new BusinessException("你输入短信验证码不正确，请重新输入");
            }
        }

        //3.校验密码是否相等
        if (!password.equals(passwordRepeat)) {
            throw new BusinessException("你输入的两次密码不相同，请重新输入");
        }

        //4.添加数据库
        User user = map2User(map);
        Logininfo logininfo = new Logininfo();
        BeanUtil.copyProperties(user, logininfo);//克隆，把user实体类跟logininfo实体类相同的字段辅助过去
        logininfo.setType(1); //类型 - 0管理员，1用户
        logininfoMapper.add(logininfo);//添加t_logininfo表，回显自增长id
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user); //添加t_user表

    }

    //填写t_user表数据
    private User map2User(Map<String, String> map) {
        User user = new User();
        user.setUsername(map.get("phone"));
        user.setPhone(map.get("phone"));
        String salt = RandomUtil.randomString(32);//盐值
        String md5psw = SecureUtil.md5(map.get("password") + salt);
        user.setSalt(salt);
        user.setPassword(md5psw);
        user.setState(1);
        return user;
    }

    //验证邮箱格式是否正确的正则表达式
    final static Pattern partern = Pattern.compile("[a-zA-Z0-9]+[\\.]{0,1}[a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-zA-Z]+");

    //邮箱注册
    @Override
    @Transactional
    public void registerEmail(Map<String, String> map) {
        String email = map.get("email");//密码
        String password = map.get("password");//密码
        String passwordRepeat = map.get("passwordRepeat");//确认密码
        //1.校验空值
        if (StrUtil.isBlank(email) ||
                StrUtil.isBlank(password) || StrUtil.isBlank(passwordRepeat)) {
            throw new BusinessException("请填写完整信息");
        }
        //2.校验邮箱的准确性
        if (!partern.matcher(email).matches()){
            throw new BusinessException("你输入的邮箱格式不正确，请重新输入");
        }
        //3.校验密码是否相等
        if (!password.equals(passwordRepeat)) {
            throw new BusinessException("你输入的两次密码不相同，请重新输入");
        }

        //添加数据库
        User user = new User();
        user.setEmail(email);
        String salt = RandomUtil.randomString(32);//盐值
        String md5psw = SecureUtil.md5(map.get("password") + salt);
        user.setSalt(salt);
        user.setPassword(md5psw);
        user.setState(0);//员工状态 - 1启用，0禁用

        Logininfo logininfo = new Logininfo();
        BeanUtil.copyProperties(user,logininfo);
        logininfo.setType(1);//类型 - 0管理员，1用户
        logininfoMapper.add(logininfo);

        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            //发送复杂邮件的工具类
            //true - 能够添加附件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("2567209139@qq.com");
            helper.setSubject("邮箱注册激活邮件");
            //true - 能够再内容中编写html标签 - 会解析
            helper.setText("<h1>你的邮箱注册!!!</h1>" +
                    "<a href='http://127.0.0.1:8080/user/activation/"+user.getId()+"'>点击该链接激活</a>",true);
            //收件人
            helper.setTo(email);
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    //在qq邮箱激活员工状态 - 1启用，0禁用
    @Override
    public void activation(Long id, HttpServletResponse response) {
        User user = userMapper.findOne(id);
        user.setState(1); // 员工状态 - 1启用，0禁用
        userMapper.update(user);
        Logininfo logininfo = logininfoMapper.findOne(user.getLogininfoId());
        logininfo.setState(1);  //启用状态：1可用，0禁用
        logininfoMapper.update(logininfo);

        response.setContentType("text/html;charset=UTF-8");
        try {
            response.getWriter().print("<h1 style='color:green;'>激活成功!!!3秒后跳转登录页面</h1>" +
                    "<script>\n" +
                    "  window.setTimeout(function () {\n" +
                    "    location.href = 'http://127.0.0.1/login.html'\n" +
                    "  },3000)\n" +
                    "</script>");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
